package com.leyou.item.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.pojo.PageResult;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.pojo.Brand;
import com.leyou.item.service.BrandService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class BrandServiceImpl implements BrandService {

    @Autowired
    private BrandMapper brandMapper;

    @Override
    public PageResult<Brand> page(Integer page, Integer rows, String sortBy, Boolean desc, String key) {
        PageHelper.startPage(page, rows);
        Example example = new Example(Brand.class);
        if (StringUtils.isNotBlank(sortBy)) {
            //这个方法相当于写好了sql语句的Order By
            example.setOrderByClause(sortBy + (desc ? " DESC" : " ASC"));
        }
        if (StringUtils.isNotBlank(key)) {
            example.createCriteria().andLike("name", "%" + key + "%").orEqualTo("letter", key.toUpperCase());
        }
        Page<Brand> brandPage = (Page<Brand>) brandMapper.selectByExample(example);
        //根据查询结果封装分页结果
        return new PageResult<>(brandPage.getTotal(), brandPage);
    }

    @Override
    @Transactional   //开启事务管理
    public void addBrand(Brand brand, List<Long> cids) {
        //直接保存品牌并回显id
        this.brandMapper.insertSelective(brand);
        //循环保存品牌和分类的id到tb_category_brand表
        cids.forEach(cid -> this.brandMapper.insertCategoryBrand(cid, brand.getId()));
    }

    @Override
    @Transactional
    public void updateBrand(Brand brand, List<Long> cids) {
        //品牌brand由于有id,所以可以直接修改
        this.brandMapper.updateByPrimaryKeySelective(brand);
        //修改分类有可能之前的分类都没有,而又添加一个新的分类,所以这里直接删除原来的所有分类并重新添加
        this.brandMapper.deleteCategory(brand.getId());
        //循环保存品牌和分类的id到tb_category_brand表
        cids.forEach(cid -> {
            this.brandMapper.insertCategoryBrand(cid, brand.getId());
        });
    }

    @Override
    public String queryNameByIds(Long bid) {
        Brand brand = this.brandMapper.selectByPrimaryKey(bid);
        return brand.getName();
    }

    @Override
    public List<Brand> queryBrandByCategory(Long cid) {
        return this.brandMapper.queryByCategoryId(cid);
    }

    @Override
    public Brand queryBrandById(Long bid) {
        return this.brandMapper.selectByPrimaryKey(bid);
    }

    @Override
    public List<Brand> queryBrandByIds(List<Long> bids) {
        return this.brandMapper.selectByIdList(bids);
    }
}
